package chances.system.operator.repo;

import static org.springframework.data.jpa.repository.query.QueryUtils.toOrders;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;

import chances.system.operator.entity.Operator;

public class OperatorRepositoryImpl {
	
	@PersistenceUnit
    private EntityManagerFactory emf;
	
	public Page<Operator> search(@Param("loginName")String loginName, Pageable pageable){

		EntityManager em = emf.createEntityManager();		
		CriteriaBuilder cb = em.getCriteriaBuilder(); 
        CriteriaQuery<Operator> cq = cb.createQuery(Operator.class); 
        Root<Operator> root = cq.from(Operator.class); 
        Path<String> sqlLoginName = root.get("loginName"); 
        Path<String> sqlStatus = root.get("status"); 
        
        List<Predicate> predicates = new ArrayList<Predicate>();
    	predicates.add(cb.notEqual(sqlStatus, Operator.STATUS_DELETED));
		if (loginName != null) {
	    	predicates.add(cb.like(sqlLoginName, "%" + loginName + "%"));
		}
        if (predicates.size() > 0) {
        	Predicate [] predicatesArr = 
        			predicates.toArray(new Predicate[predicates.size()]);
        	cq = cq.where(cb.and(predicatesArr));
            cq = cq.orderBy(toOrders(pageable.getSort(), root, cb));
		}
        cq = cq.orderBy(toOrders(pageable.getSort(), root, cb));

        List<Operator> sql_count  = em.createQuery(cq).getResultList(); 
        
        List<Operator> sql_list  = em.createQuery(cq)
        		.setFirstResult(pageable.getPageNumber()*pageable.getPageSize())
        		.setMaxResults(pageable.getPageSize()).getResultList();
        em.close();
		
        Page<Operator> pageImpl = new PageImpl<Operator>(sql_list, pageable, sql_count.size());
        return pageImpl; 
	}
}
